<!-- pages/login/components/mobile.vue -->
<script setup lang="ts">
  import { getCodeApi, getLoginApi } from '@/pages/apis/user'
  import { useUserStore } from '@/stores/user'
  import { ref } from 'vue'

  const form = ref<UniHelper.UniFormsInstance>()
  const isShowCountDown = ref(false)
  const getMobileCode = async () => {
    await form.value?.validateField?.(['mobile'])
    isShowCountDown.value = true
    const res = await getCodeApi({
      mobile: formData.value.mobile,
      type: 'login',
    })
    formData.value.code = res.code
  }

  const formData = ref({
    mobile: '13230000020',
    code: '',
  })
  const formRules: UniHelper.UniFormsRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请填写手机号' },
        { pattern: '^1[3-9]\\d{9}$', errorMessage: '请输入正确的手机号' },
      ],
    },
    code: {
      rules: [
        { required: true, errorMessage: '请填写验证码' },
        { pattern: '^\\d{6}$', errorMessage: '请输入6位数字验证码' },
      ],
    },
  }

  const onSubmit = async () => {
    try {
      await form.value?.validate?.()
      if (!isAgree.value) {
        return (
          uni.showToast({
            title: '请勾选同意协议',
            icon: 'error',
          }),
          (isAgree.value = true)
        )
      }

      const res = await getLoginApi(formData.value)
      // console.log(res)
      const userStore = useUserStore()
      userStore.setToken(res.token)
      userStore.userId = res.id
      uni.showToast({ title: '登录成功' })
      uni.switchTab({ url: '/pages/index/index' })
    } catch (error) {
      console.log(error)
    }
  }
  const isAgree = ref(false)
</script>

<template>
  <uni-forms class="login-form" ref="form" :model="formData" :rules="formRules">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
        v-model="formData.code"
      />
      <text class="text-button" v-if="isShowCountDown === false" @click="getMobileCode()"
        >获取验证码</text
      >
      <view class="text-button" v-else>
        <uni-countdown
          :show-day="false"
          :show-hour="false"
          :show-minute="false"
          :second="59"
          @timeup="isShowCountDown = false"
        />
        秒后重新发送
      </view>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit()">登 录</button>
    {{ formData }}
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
